<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGetToken">获取Token</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleGetToken"
          v-hasPermi="['system:token:get']"
        >获取Token</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClearAllCache"
          :loading="clearAllLoading"
          v-hasPermi="['system:token:clear']"
        >清空所有缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- Token获取表单 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>Token获取</span>
      </div>
      <el-form ref="tokenForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="接口地址" prop="apiUrl">
              <el-input v-model="form.apiUrl" placeholder="请输入接口地址，如：http://localhost:8080/api/login" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="loading">获取Token</el-button>
              <el-button @click="resetForm">重置</el-button>
              <el-button type="warning" @click="handleClearCache" :loading="clearLoading">清空缓存</el-button>
              <el-button type="success" @click="handleRefreshCache" :loading="refreshLoading">重刷缓存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- Token结果显示 -->
    <el-card class="box-card" v-if="tokenInfo">
      <div slot="header" class="clearfix">
        <span>Token结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="copyToken">复制Token</el-button>
      </div>
      
      <!-- Token过期倒计时 -->
      <div v-if="tokenInfo.expireTime" class="token-expire-info">
        <el-alert
          :title="expireMessage"
          :type="expireAlertType"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;">
        </el-alert>
        <div class="countdown-display">
          <span class="countdown-label">剩余时间：</span>
          <span class="countdown-time" :class="countdownClass">{{ formatCountdown(remainingTime) }}</span>
        </div>
      </div>
      
      <el-input
        v-model="tokenInfo.token"
        type="textarea"
        :rows="6"
        placeholder="Token将在这里显示"
        readonly
      />
    </el-card>
  </div>
</template>

<script>
import { getToken, clearAllTokenCache, clearTokenCache, refreshTokenCache } from "@/api/system/token";

export default {
  name: "Token",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 清空缓存加载状态
      clearLoading: false,
      // 重刷缓存加载状态
      refreshLoading: false,
      // 清空所有缓存加载状态
      clearAllLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {},
      // 表单参数
      form: {
        username: "",
        password: "",
        apiUrl: "http://150.158.123.33:38080/login"
      },
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        apiUrl: [
          { required: true, message: "接口地址不能为空", trigger: "blur" },
          { 
            pattern: /^https?:\/\/.+/, 
            message: "请输入有效的URL地址", 
            trigger: "blur" 
          }
        ]
      },
      // Token信息
      tokenInfo: null,
      // 倒计时定时器
      countdownTimer: null,
      // 剩余时间（毫秒）
      remainingTime: 0
    };
  },
  computed: {
    // 过期提示消息
    expireMessage() {
      if (this.remainingTime <= 0) {
        return "Token已过期";
      } else if (this.remainingTime <= 5 * 60 * 1000) { // 5分钟
        return "Token即将过期，请及时刷新";
      } else {
        return "Token有效";
      }
    },
    // 过期提示类型
    expireAlertType() {
      if (this.remainingTime <= 0) {
        return "error";
      } else if (this.remainingTime <= 5 * 60 * 1000) { // 5分钟
        return "warning";
      } else {
        return "success";
      }
    },
    // 倒计时样式类
    countdownClass() {
      if (this.remainingTime <= 0) {
        return "expired";
      } else if (this.remainingTime <= 5 * 60 * 1000) { // 5分钟
        return "warning";
      } else {
        return "normal";
      }
    }
  },
  created() {
    this.getList();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      // 这里可以添加获取历史记录的逻辑
    },
    /** 重置按钮操作 */
    resetForm() {
      this.form = {
        username: "",
        password: "",
        apiUrl: "http://150.158.123.33:38080/login"
      };
      this.tokenInfo = null;
      this.clearCountdown();
      this.resetForm("tokenForm");
    },
    /** 获取Token按钮操作 */
    handleGetToken() {
      this.submitForm();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["tokenForm"].validate(valid => {
        if (valid) {
          this.loading = true;
          getToken(this.form).then(response => {
            this.$modal.msgSuccess("获取Token成功");
            this.tokenInfo = response.data;
            this.startCountdown();
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        }
      });
    },
    /** 复制Token */
    copyToken() {
      if (this.tokenInfo && this.tokenInfo.token) {
        const textarea = document.createElement('textarea');
        textarea.value = this.tokenInfo.token;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        this.$modal.msgSuccess("Token已复制到剪贴板");
      }
    },
    /** 开始倒计时 */
    startCountdown() {
      this.clearCountdown();
      
      if (this.tokenInfo && this.tokenInfo.expireTime) {
        this.updateRemainingTime();
        
        this.countdownTimer = setInterval(() => {
          this.updateRemainingTime();
          
          if (this.remainingTime <= 0) {
            this.clearCountdown();
          }
        }, 1000);
      }
    },
    /** 更新剩余时间 */
    updateRemainingTime() {
      if (this.tokenInfo && this.tokenInfo.expireTime) {
        this.remainingTime = Math.max(0, this.tokenInfo.expireTime - Date.now());
      }
    },
    /** 清除倒计时 */
    clearCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
    },
    /** 格式化倒计时显示 */
    formatCountdown(milliseconds) {
      if (milliseconds <= 0) {
        return "00:00:00";
      }
      
      const totalSeconds = Math.floor(milliseconds / 1000);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;
      
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },
    /** 清空指定缓存 */
    handleClearCache() {
      this.$refs["tokenForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('确认清空当前用户的Token缓存吗？').then(() => {
            this.clearLoading = true;
            const params = {
              username: this.form.username,
              apiUrl: this.form.apiUrl
            };
            clearTokenCache(params).then(response => {
              this.$modal.msgSuccess("缓存清空成功");
              this.clearLoading = false;
            }).catch(() => {
              this.clearLoading = false;
            });
          });
        }
      });
    },
    /** 重刷缓存 */
    handleRefreshCache() {
      this.$refs["tokenForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('确认重新刷新当前用户的Token缓存吗？').then(() => {
            this.refreshLoading = true;
            refreshTokenCache(this.form).then(response => {
              this.$modal.msgSuccess("缓存刷新成功");
              this.tokenInfo = response.data;
              this.startCountdown();
              this.refreshLoading = false;
            }).catch(() => {
              this.refreshLoading = false;
            });
          });
        }
      });
    },
    /** 清空所有缓存 */
    handleClearAllCache() {
      this.$modal.confirm('确认清空所有Token缓存吗？此操作将清空系统中所有用户的Token缓存。').then(() => {
        this.clearAllLoading = true;
        clearAllTokenCache().then(response => {
          this.$modal.msgSuccess("所有缓存清空成功");
          this.clearAllLoading = false;
        }).catch(() => {
          this.clearAllLoading = false;
        });
      });
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.token-expire-info {
  margin-bottom: 15px;
}

.countdown-display {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.countdown-label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.countdown-time {
  font-family: 'Courier New', monospace;
  font-size: 18px;
  font-weight: bold;
  padding: 5px 10px;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
}

.countdown-time.normal {
  color: #67c23a;
  border-color: #67c23a;
}

.countdown-time.warning {
  color: #e6a23c;
  border-color: #e6a23c;
  animation: blink 1s infinite;
}

.countdown-time.expired {
  color: #f56c6c;
  border-color: #f56c6c;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.5; }
}
</style>